package com.dog.view.converter;

import com.dog.model.ContactPerson;
import com.dog.service.IContactPersonService;
import com.dog.spring.ServiceFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * User: Kuttubek Aidaraliev
 * Date: 14.05.2010
 * Time: 14:20:27
 */
public class ContactPersonConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        IContactPersonService contactPersonService = ServiceFactory.getContactPersonService();
        ContactPerson contactPerson = null;
        try {
            contactPerson = contactPersonService.get(new Long(s));
        } catch (Exception e){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Invalid ContactPerson selected. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
        if(contactPerson == null){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                        "ContactPerson not found. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return contactPerson;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
         if(o instanceof ContactPerson) {
            ContactPerson contactPerson = (ContactPerson)o;
            return contactPerson.getId().toString();
        }
        else throw new IllegalArgumentException("Argument must be ContactPerson object!");
    }

}
